<#--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->
<#--
    Action Codes
    00 = Empty
    01 = Current Point
    021 = GPS Tracking
    022 = GPS list Tracking
    03 = Edit Geo Point
-->
<#if parameters.action?has_content>
    <#assign action = parameters.action/>
    <#else>
    <#assign action = "00"/>
</#if>
<#if action == "021" && productGeoPointList?has_content>
<script>
  $(function() {
    $("#slider-range-min").slider({
      range: "min",
      value: 100,
      min: 1,
      max: 100,
      slide: function( event, ui ) {
        var icons = line.get('icons');
        icons[0].offset = ui.value + '%';
        line.set('icons', icons);
        $("#offset").val(ui.value);
      }
    });
    $( "#amount" ).val( "$" + $( "#slider-range-min" ).slider( "value" ) );
  });
  </script>

  <label for="offset">Offset:</label>
  <input type="text" id="offset" value="100" size="3" readonly="readonly">
  <div id="slider-range-min"></div>
<br/>
</#if>

<style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map-canvas { height: 450px; }
</style>
<div id="map-canvas"/>

<script type="text/javascript">
    
    var map = null;
</script>
<#-- 00 = Empty-->
<#if action == "00">
<script type="text/javascript">
    function initialize() {
        var mapOptions = {
          center: new google.maps.LatLng(15.220589019578128, 100.9357912838459),
          zoom: 5
        };
        map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
      }
    initialize();

</script>
</#if>

<#-- 01 = Geo Point -->
<#if action == "01">
<script type="text/javascript">
    function initialize() {
        var myLatlng = new google.maps.LatLng(${productGeoPoint.latitude},${productGeoPoint.longitude});
        var mapOptions = {
          zoom: ${productGeoPoint.elevation?default(10)},
          center: myLatlng
        }
        map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
        
        // To add the marker to the map, use the 'map' property
        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title:"${productGeoPoint.internalName}"
        });
    }
    initialize();
</script>
</#if>

<#-- 021 = GPS Tracking -->
<#if action == "021" && productGeoPointList?has_content>
<script type="text/javascript">
    // icon url
    dotImage = '<@ofbizContentUrl fullPath="true">gpsmgr/images/dot.png</@ofbizContentUrl>';
    // This example adds an animated symbol to a polyline.
    bounds = new google.maps.LatLngBounds();
    <#list productGeoPointList as productGeoPoint>
    bounds.extend(new google.maps.LatLng(${productGeoPoint.latitude},${productGeoPoint.longitude}));
    </#list>
    line = null;
    nowGeoPointId = "${productGeoPoint}";
    function initialize() {
      var mapOptions = {
        center: new google.maps.LatLng(${productGeoPoint.latitude},${productGeoPoint.longitude}),
        zoom: 10,
        suppressPolylines : true
        //, mapTypeId: google.maps.MapTypeId.TERRAIN
      };
    
      map = new google.maps.Map(document.getElementById('map-canvas'),
          mapOptions);
      lineCoordinates = null;
      lineCoordinates = [
        <#list productGeoPointList as productGeoPoint>
        <#if productGeoPoint_index = 0>
            new google.maps.LatLng(${productGeoPoint.latitude},${productGeoPoint.longitude})
            <#else>
            , new google.maps.LatLng(${productGeoPoint.latitude},${productGeoPoint.longitude})
        </#if>
        </#list>
      ];
    
      // Define the symbol, using one of the predefined paths ('CIRCLE')
      // supplied by the Google Maps JavaScript API.
      var lineSymbol = {
        path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
        scale: 5,
        strokeColor: '#808080'
      };
    
      // Create the polyline and add the symbol to it via the 'icons' property.
      line = new google.maps.Polyline({
        path: lineCoordinates,
        icons: [{
          icon: lineSymbol,
          offset: '100%'
        }],
        map: map
      });
      
      // Create markers
      <#list productGeoPointList as productGeoPoint>
      var marker_${productGeoPoint.geoPointId} = new google.maps.Marker({
          position: new google.maps.LatLng(${productGeoPoint.latitude},${productGeoPoint.longitude}),
          icon: dotImage,
          map: map,
          title: 'Latitude: ${productGeoPoint.latitude} \n Longitude: ${productGeoPoint.longitude} \n Speed: ${productGeoPoint.speed} \n Time: ${productGeoPoint.fromDate}'
      });
      </#list>
      
      getNextGeoPoint();
    }
    function getNextGeoPoint() {
        var count = 0;
        window.setInterval(function() {
            
            var dataSet = {};
            dataSet = {"productId" : "${parameters.productId}"};
            jQuery.ajax({
                type: "POST",
                url: "getLastProductGeoPoint",
                data: dataSet,
                error: function(msg) {
                    alert("An error occurred loading content! : " + msg);
                },
                success: function(msg) {
                    if (checkErrorJson(msg)) {
                        if (nowGeoPointId != msg.geoPointId) {
                            // change lineSymbol moving
                            var lineSymbol = {
                                path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
                                scale: 5,
                                strokeColor: '#008000'
                              };
                            line.setOptions({"icons": [{icon: lineSymbol, offset: '100%'}]});
                            
                            nowGeoPointId = msg.geoPointId;
                            var path = line.getPath();
                            // Because path is an MVCArray, we can simply append a new coordinate
                            // and it will automatically appear.
                            path.push(new google.maps.LatLng(msg.latitude, msg.longitude));
                            var marker = new google.maps.Marker({
                                position: new google.maps.LatLng(msg.latitude, msg.longitude),
                                icon: dotImage,
                                map: map,
                                title: 'Latitude: ' + msg.latitude
                                        + ' \n Longitude: ' + msg.longitude
                                        + ' \n Speed: ' + msg.speed
                                        + ' \n Time: ' + msg.fromDate
                            });
                        } else {
                            // change lineSymbol stop
                            var lineSymbol = {
                                path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
                                scale: 5,
                                strokeColor: '#808080'
                              };
                            line.setOptions({"icons": [{icon: lineSymbol, offset: '100%'}]});
                        }
                    }
                }
            });
      }, 10000);
    }
    initialize();
    <#if productGeoPointList?has_content>
    map.fitBounds(bounds); 
    map.setCenter(bounds.getCenter());
    </#if>
</script>
</#if>

<#-- 022 = GPS List Tracking -->
<#if action == "022">
<script type="text/javascript">
bounds = new google.maps.LatLngBounds();
<#list productRoleList as productRole>
<#assign productGeoPointList = delegator.findByAnd("ProductGeoPointView", Static["org.ofbiz.base.util.UtilMisc"].toMap("productId", productRole.productId), null, false)/>
<#assign productGeoPoint = nullField/>
<#if (productGeoPointList.size() > 0)>
    <#assign productGeoPoint = productGeoPointList.get(productGeoPointList.size() - 1)/>
</#if>
<#if productGeoPoint?has_content>
    // This example adds an animated symbol to a polyline.
    
    line_${productRole.productId} = null;
    nowGeoPointId_${productRole.productId} = "${productGeoPoint.geoPointId}";
    <#list productGeoPointList as productGeoPoint>
    bounds.extend(new google.maps.LatLng(${productGeoPoint.latitude},${productGeoPoint.longitude}));
    </#list>
    function initialize_${productRole.productId} () {
      <#if productRole_index = 0>
      var mapOptions = {
        center: new google.maps.LatLng(${productGeoPoint.latitude},${productGeoPoint.longitude}),
        zoom: 10
        //, mapTypeId: google.maps.MapTypeId.TERRAIN
      };
      map = new google.maps.Map(document.getElementById('map-canvas'),
          mapOptions);
      </#if>
      lineCoordinates_${productRole.productId} = [
        <#list productGeoPointList as productGeoPoint>
        <#if productGeoPoint_index = 0>
            new google.maps.LatLng(${productGeoPoint.latitude},${productGeoPoint.longitude})
            <#else>
            , new google.maps.LatLng(${productGeoPoint.latitude},${productGeoPoint.longitude})
        </#if>
        </#list>
      ];
    
      // Define the symbol, using one of the predefined paths ('CIRCLE')
      // supplied by the Google Maps JavaScript API.
      var lineSymbol = {
        path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
        scale: 5,
        strokeColor: '#808080'
      };
    
      // Create the polyline and add the symbol to it via the 'icons' property.
      line_${productRole.productId} = new google.maps.Polyline({
        path: lineCoordinates_${productRole.productId},
        icons: [{
          icon: lineSymbol,
          offset: '100%'
        }],
        map: map
      });
      getNextGeoPoint_${productRole.productId}();
    }
    function getNextGeoPoint_${productRole.productId}() {
        var count = 0;
        window.setInterval(function() {
            
            var dataSet = {};
            dataSet = {"productId" : "${productRole.productId}"};
            jQuery.ajax({
                type: "POST",
                url: "getLastProductGeoPoint",
                data: dataSet,
                error: function(msg) {
                    alert("An error occurred loading content! : " + msg);
                },
                success: function(msg) {
                    if (checkErrorJson(msg)) {
                        if (nowGeoPointId_${productRole.productId} != msg.geoPointId) {
                            // change lineSymbol moving
                            var lineSymbol = {
                                path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
                                scale: 5,
                                strokeColor: '#008000'
                              };
                            line_${productRole.productId}.setOptions({"icons": [{icon: lineSymbol, offset: '100%'}]});
                            
                            nowGeoPointId_${productRole.productId} = msg.geoPointId;
                            var path = line_${productRole.productId}.getPath();
                            // Because path is an MVCArray, we can simply append a new coordinate
                            // and it will automatically appear.
                            path.push(new google.maps.LatLng(msg.latitude, msg.longitude));
                        } else {
                            // change lineSymbol stop
                            var lineSymbol = {
                                path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
                                scale: 5,
                                strokeColor: '#808080'
                              };
                            line_${productRole.productId}.setOptions({"icons": [{icon: lineSymbol, offset: '100%'}]});
                        }
                    }
                }
            });
      }, 10000);
    }
    initialize_${productRole.productId}();

</#if>
</#list>
    <#if productGeoPoint?has_content>
    map.fitBounds(bounds); 
    map.setCenter(bounds.getCenter());
    </#if>
</script>
</#if>


<#-- 03 = Edit Geo Point -->
<#if action == "03">
<input id="pac-input" class="controls" type="text" placeholder="Search Box" size="25">
<script type="text/javascript">
    var markers = [];
    
    function initialize() {
        var mapOptions = {
                center: new google.maps.LatLng(15.220589019578128, 100.9357912838459),
                zoom: 5
            };
        map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
        google.maps.event.addListener(map, 'click', function (event) {
            $('#EditGeoPoint_latitude').val(event.latLng.lat());
            $('#EditGeoPoint_longitude').val(event.latLng.lng());
            $('#EditGeoPoint_elevation').val(map.getZoom());
            deleteMarkers();
            addMarker(event.latLng);
            setAllMap(map);
        });
        // Create the search box and link it to the UI element.
        var input = document.getElementById('pac-input');
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

        var searchBox = new google.maps.places.SearchBox(input);
        google.maps.event.addListener(searchBox, 'places_changed', function() {
            var places = searchBox.getPlaces();
    
            for (var i = 0, marker; marker = markers[i]; i++) {
              marker.setMap(null);
            }
        
            // For each place, get the icon, place name, and location.
            markers = [];
            var bounds = new google.maps.LatLngBounds();
            for (var i = 0, place; place = places[i]; i++) {
              var image = {
                url: place.icon,
                size: new google.maps.Size(71, 71),
                origin: new google.maps.Point(0, 0),
                anchor: new google.maps.Point(17, 34),
                scaledSize: new google.maps.Size(25, 25)
              };
        
              // Create a marker for each place.
              var marker = new google.maps.Marker({
                map: map,
                icon: image,
                title: place.name,
                position: place.geometry.location
              });
        
              markers.push(marker);
        
              bounds.extend(place.geometry.location);
            }
        
            map.fitBounds(bounds);
      });
      // [END region_getplaces]
    
      // Bias the SearchBox results towards places that are within the bounds of the
      // current map's viewport.
      google.maps.event.addListener(map, 'bounds_changed', function() {
        var bounds = map.getBounds();
        searchBox.setBounds(bounds);
      });
      
      google.maps.event.addListener(map, 'zoom_changed', function() {
        $('#EditGeoPoint_elevation').val(map.getZoom());
      });
    }
    // Add a marker to the map and push to the array.
    function addMarker(location) {
      var marker = new google.maps.Marker({
        position: location,
        map: map,
        draggable:true
      });
      google.maps.event.addListener(marker, 'dragend', function(event) {
        $('#EditGeoPoint_latitude').val(event.latLng.lat());
        $('#EditGeoPoint_longitude').val(event.latLng.lng());
        $('#EditGeoPoint_elevation').val(map.getZoom());
        testSendGPSPoint("111111111111111", event.latLng.lat(), event.latLng.lng());
      });
      markers.push(marker);
    }
    
    // Sets the map on all markers in the array.
    function setAllMap(map) {
      for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(map);
      }
    }
    
    // Removes the markers from the map, but keeps them in the array.
    function clearMarkers() {
      setAllMap(null);
    }
    
    // Shows any markers currently in the array.
    function showMarkers() {
      setAllMap(map);
    }
    
    // Deletes all markers in the array by removing references to them.
    function deleteMarkers() {
      clearMarkers();
      markers = [];
    }
   initialize();
    function testSendGPSPoint(productId, latitude, longitude) {
        var dataSet = {"productId" : productId, "latitude" : latitude, "longitude" : longitude};
        jQuery.ajax({
            type: "POST",
            url: "receiveProductGeoPoint",
            data: dataSet,
            error: function(msg) {
                alert("An error occurred loading content! : " + msg);
            },
            success: function(msg) {
                if (checkErrorJson(msg)) {
                    //alert("productId: " + productId + "\n latitude: " + latitude + "\n longitude: " + longitude);
                }
            }
        });
    }
</script>
</#if>
